//引入用户数据库模块
const { json } = require("express")
const CollectionsModel_DB = require("../models/CollectionsModel_DB")
//引入发送前端工具
const Response = require("../utils/ResponseEntity")

class CollectionController {
    //获取所有类型
    async findAll(req, res, next) {
        try {
            //接收前端传的学生id
            const { id } = req.query
            const data = await CollectionsModel_DB.find({ studentId: id }).populate("exerciseId")
            if (data.length) res.send(Response.success({ msg: "查询成功", data }))
            else res.send(Response.error({ msg: "查询失败" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }
    //接收前端发送的收藏试题
    getStuCollections(req, res, next) {
        try {
            //接收前端发送的学生id 和 收藏试题数组
            let { studentId, collectionsArr } = req.body
            collectionsArr = JSON.parse(collectionsArr)
            if (studentId && collectionsArr.length) {
                collectionsArr.forEach(async (element) => {
                    if (element != undefined) {
                        await CollectionsModel_DB.create({ studentId, exerciseId: element })
                    }
                });
                res.send(Response.success({ msg: "保存成功" }))
            } else res.send(Response.error({ msg: "数据为空" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }

    //根据学生id和试题id删除收藏试题
    async deleteByStuAndExerciseId(req, res, next) {
        try {
            const { studentId, exerciseId } = req.body
            //删除数据
            const ress = await CollectionsModel_DB.deleteOne({ studentId, exerciseId })
            console.log(ress);
            res.send(Response.success({ msg: "删除成功" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }
}

const collection = new CollectionController()
module.exports = collection